package com.yun.platform.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yun.platform.config.cache.CacheUserLocal;
import com.yun.platform.config.cache.UserCache;
import com.yun.platform.config.dto.RData;
import com.yun.platform.excption.BizException;
import com.yun.platform.util.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author laich
 * @date 2021/9/10 10:41
 * jwt 用户拦截器  @RestControllerAdvice 无法拦截Filter内抛出异常
 */
@Slf4j
@RestController
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        // 需要工具类JWTUtil来解析前端的请求头: Authorization
        JWTUtil util = new JWTUtil();
        String jwt = request.getHeader("Authorization");

        try {
            if (!StringUtils.isEmpty(jwt)) {
                Claims c;
                c = util.parseJWT(jwt);
                // 通过Claim对象,可以获取在jwt中保存的特征(Map)
                UserCache userCache = JSON.parseObject(c.getSubject(), UserCache.class);
                log.info(JSON.toJSONString(userCache,true));
                CacheUserLocal.set(userCache);
                return true;
            }
        } catch (Exception e) {
            log.error("error",e);
            outError(response,"请登录！");
            return false;
        }
        // 当返回false的时候, 表示被拦截住,没法访问controller
        outError(response,"token解析错误，验证失败");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private void outError(HttpServletResponse response,String msg) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-type", "application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(RData.fail(msg)));
    }

}
